package com.youlai.system.plugin.easyexcel;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.youlai.system.model.entity.SysCategory;
import com.youlai.system.model.entity.SysCourse;
import com.youlai.system.model.vo.CourseCategoryImportVO;
import com.youlai.system.service.SysCategoryService;
import com.youlai.system.service.SysCourseService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CourseCategoryImportListener extends MyAnalysisEventListener<CourseCategoryImportVO> {

    //记录之前的临时故障分类
    private String tempCategory;

    private final SysCategoryService categoryService;

    private final SysCourseService courseService;

    public CourseCategoryImportListener() {
        this.categoryService = SpringUtil.getBean(SysCategoryService.class);
        this.courseService = SpringUtil.getBean(SysCourseService.class);
    }

    @Override
    public String getMsg() {
        // 总结信息
        String summaryMsg = StrUtil.format("导入故障分类科目记录结束：成功{}条，失败{}条；<br/>{}", validCount, invalidCount, msg);
        return summaryMsg;
    }

    @Override
    public void invoke(CourseCategoryImportVO courseCategoryImportVO, AnalysisContext analysisContext) {
        log.info("解析到一条故障分类科目记录数据:{}", JSONUtil.toJsonStr(courseCategoryImportVO));
        if (StrUtil.isNotBlank(courseCategoryImportVO.getCategory())) {
            tempCategory = courseCategoryImportVO.getCategory();
        }

        SysCategory category = categoryService.getByContentEqual(tempCategory);
        if (category == null) {
            category = categoryService.saveByContent(tempCategory);
        }

        SysCourse course = courseService.getByContentEqual(courseCategoryImportVO.getCourse());
        if (course == null) {
            course = courseService.saveByContent(courseCategoryImportVO.getCourse());
        }
        course.setCategoryId(category.getId());
        courseService.updateById(course);
        validCount++;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
